package com.bifang.common.aspect;

import com.bifang.common.exception.AppException;
import com.bifang.common.util.ErrorUtil;
import com.bifang.common.util.OplogUtil;
import com.bifang.common.util.SessionUtil;
import com.bifang.common.vo.AppResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/** 统一处理异常信息 */
@ControllerAdvice
public class ErrorController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler
    @ResponseBody
    public AppResponse handleAndReturnData(
            HttpServletRequest request, HttpServletResponse response, Exception ex) {
        OplogUtil.removeOplogInfo();
        SessionUtil.removeSesionInfo();
        //integration层校验参数报错处理
        if (ex instanceof ConstraintViolationException) {
            ConstraintViolation<?> violation =
                    ((ConstraintViolationException) ex)
                            .getConstraintViolations().stream().findFirst().get();
            logger.error("统一异常处理:", ex);
            return ErrorUtil.errorResponse(new AppException(violation.getMessage()));
        }

        logger.error("统一异常处理:", ex);
        return ErrorUtil.errorResponse(ex);
    }
}
